﻿using System.Text;

namespace Homework18
{
    public class Program
    {           
        /// <summary>
    /// 运算
    /// </summary>
            static void main()
            {
                Console.WriteLine("请输入一个四则运算表达式（例如：3.2+2*6）：");
                string? input = Console.ReadLine();

                try
                {
                    double result = EvaluateExpression(input);
                    Console.WriteLine("结果是：" + result);
                }
                catch (Exception ex)
                {
                    Console.WriteLine("表达式错误：" + ex.Message);
                }
            }

            public static double EvaluateExpression(string expression)
            {
                // 移除空格
                expression = new string(expression.Where(c => !char.IsWhiteSpace(c)).ToArray());
                //建立两个栈，一个存放操作符，一个存放数字
                Stack<double> operandStack = new Stack<double>();
                Stack<char> operatorStack = new Stack<char>();

                int i = 0;
                while (i < expression.Length)
                {
                    char currentChar = expression[i];

                    if (char.IsDigit(currentChar) || currentChar == '.')
                    {
                        // 读取完整的数字
                        StringBuilder numberBuilder = new StringBuilder();
                        while (i < expression.Length &&
                               (char.IsDigit(expression[i]) || expression[i] == '.'))
                        {
                            numberBuilder.Append(expression[i]);
                            i++;
                        }
                        double operand = double.Parse(numberBuilder.ToString());
                        operandStack.Push(operand);
                        i--; // 因为我们在while循环中已经增加了i
                    }
                    //遇到括号
                    else if (currentChar == '(')
                    {
                        operatorStack.Push(currentChar);
                    }
                    else if (currentChar == ')')
                    {
                        while (operatorStack.Peek() != '(')
                        {//计算括号内内容
                            double operand2 = operandStack.Pop();
                            double operand1 = operandStack.Pop();
                            char op = operatorStack.Pop();
                            operandStack.Push(ApplyOperation(operand1, operand2, op));
                        }
                        operatorStack.Pop(); // 移除 '('
                    }
                    //检查优先级
                    else if (IsOperator(currentChar))
                    {
                        while (operatorStack.Count > 0 &&
                               Precedence(operatorStack.Peek()) >= Precedence(currentChar))
                        {
                            double operand2 = operandStack.Pop();
                            double operand1 = operandStack.Pop();
                            char op = operatorStack.Pop();
                            operandStack.Push(ApplyOperation(operand1, operand2, op));
                        }
                        operatorStack.Push(currentChar);
                    }

                    i++;
                }

                // 处理栈中剩余的操作符
                while (operatorStack.Count > 0)
                {
                    double operand2 = operandStack.Pop();
                    double operand1 = operandStack.Pop();
                    char op = operatorStack.Pop();
                    operandStack.Push(ApplyOperation(operand1, operand2, op));
                }

                // 栈中应该只剩下一个元素，即最终结果
                return operandStack.Pop();
            }

            static bool IsOperator(char c)
            {
                return c == '+' || c == '-' || c == '*' || c == '/';
            }

            public static int Precedence(char op)
            {
                switch (op)
                {
                    case '+':
                    case '-':
                        return 1;
                    case '*':
                    case '/':
                        return 2;
                    default:
                        return 0;
                }
            }

            static double ApplyOperation(double operand1, double operand2, char op)
            {
                switch (op)
                {
                    case '+':
                        return operand1 + operand2;
                    case '-':
                        return operand1 - operand2;
                    case '*':
                        return operand1 * operand2;
                    case '/':
                        if (operand2 == 0)
                            throw new InvalidOperationException("除数不能为零");
                        return operand1 / operand2;
                    default:
                        throw new InvalidOperationException("未知的操作符");
                }
            }
        }
    }

